<template>
  <div class="settings-section">
    <h3>账号设置</h3>
    <el-form :model="userForm" label-width="100px" class="settings-form">
      <el-form-item label="头像">
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleFileSelect">
            <img v-if="fileList.length" :src="fileList[0].url" class="avatar">
            <img v-else-if="userForm.avatarUrl" :src="fileBaseUrl() + userForm.avatarUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <el-button 
            v-if="userForm.avatarUrl" 
            type="danger" 
            size="small" 
            @click="handleAvatarDelete"
            class="delete-btn"
          >
            删除头像
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="昵称">
        <el-input v-model="userForm.nickname"></el-input>
      </el-form-item>
      
      <el-form-item label="手机号">
        <el-input v-model="userForm.phoneNumber"></el-input>
      </el-form-item>
      
      <el-form-item label="邮箱">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="saveSettings" :loading="loading">保存修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { fileBaseUrl } from '@/apis/files'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { updateUser } from '@/apis/user'
import { useUserStore } from '@/stores/userStore'
import { ref } from 'vue'
import { useFileUpload } from '@/composables/useFileUpload'

const userStore = useUserStore()
const userForm = userStore.userInfo
const loading = ref(false)
const path = 'user/avatar/'+ userForm.userId

const {
  uploadLoading,
  fileList,
  handleFileSelect,
  uploadFile,
  replaceFile,
  deleteFile,
  clearFiles
} = useFileUpload()

// 处理头像上传
const handleAvatarUpload = async () => {
  if (!fileList.value.length) {
    return
  }

  if (userForm.avatarUrl) {
    const result = await replaceFile(fileList.value[0], userForm.avatarUrl)
    if (result) {
      // 更新用户头像
      userForm.avatarUrl = result
      // 清除文件列表
      clearFiles()
    }
  } else {
    // 如果没有旧头像，使用普通上传
    const result = await uploadFile(path)
    if (result) {
      // 更新用户头像
      userForm.avatarUrl = result
      // 清除文件列表
      clearFiles()
    }
}
}

// 处理头像删除
const handleAvatarDelete = async () => {
  if (!userForm.avatarUrl) {
    return
  }

  const fileName = userForm.avatarUrl.split('/').pop()
  const success = await deleteFile(path, fileName)
  if (success) {
    userForm.avatarUrl = ''
  }
}

const saveSettings = async () => {
  loading.value = true
  try {
    // 先上传头像（如果有）
    if (fileList.value.length) {
      await handleAvatarUpload()
    }

    const res = await updateUser(userForm)
    if (res.code === '0') {
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.settings-section {
  padding: 20px;
}

.settings-form {
  max-width: 500px;
  margin-top: 20px;
}

.avatar-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.delete-btn {
  margin-left: 10px;
}
</style> 